# coding=utf8
from django.contrib import admin
from django.http import HttpResponse
from tussin.ads.models import AdBlock,AdItem
from tussin.ads.forms import AdItemForm

class AdBlockAdmin(admin.ModelAdmin):
    list_display = ['name', 'page', 'remark']
    fields = ['name', 'page', 'remark']

    def queryset(self, request):
        qs = super(AdBlockAdmin, self).queryset(request)
        if request.user.username == 'amom':
            return qs
        else:
            return HttpResponse('你不能管理广告位')

class AdItemAdmin(admin.ModelAdmin):
    list_display = ["name", "ad_block", "editor", "created", "updated"]
    fields = ["name", "ad_type", 'ad_block', 'ad_text', 'ad_file', "ad_link"]

    def save_model(self, request, obj, form, change):
        if not change:
            obj.editor = request.user
        if request.method == "POST":
            form = AdItemForm(request.POST, request.FILES)
            if form.is_valid():
                file = ContentFile(request.FILES["ad_link"].read())
                obj.save(request.FILES['ad_link'].name, file)
        obj.save()

admin.site.register(AdBlock, AdBlockAdmin)
admin.site.register(AdItem, AdItemAdmin)
